﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model = BLL.Model;
using BLL.RepositoryInterface;
using DAL.DbEntity;
using DAL.Translator;
using System.Transactions;

namespace DAL.Repository
{
    public class OrderRepository:IOrderRepository
    {
        private string connectionString;
        public OrderRepository(string connStr)
        {
            connectionString = connStr;
        }

        public IList<Model.Product> GetProductInStock()
        {
            IList<Model.Product> products = null;
            IList<Product> productDbObjects = null;
            using (OrderContainer container = new OrderContainer(connectionString))
            {
                productDbObjects = (from p in container.Products select p).ToList<Product>();
                if (productDbObjects != null && productDbObjects.Count > 0)
                {
                    products = new List<Model.Product>();
                    foreach (Product p in productDbObjects)
                    {
                        products.Add(ProductTranslator.TranslateBusinessToDbEntity(p));
                    }
                }
            }
            return products;
        }

        public bool SaveOrderAndItems(Model.Order order)
        {
            bool saveResult = false;
            Order orderDbObjects = null;
            if (order != null)
            {
                using (OrderContainer container = new OrderContainer(connectionString))
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        try
                        {
                            orderDbObjects = OrderTranslator.TranslateBusinessToDbEntity(order, container);
                            if (order.OrderId > 0)
                            {
                                container.AcceptAllChanges();
                                container.SaveChanges();
                                
                            }
                            else
                            {
                                container.AddToOrders(orderDbObjects);
                                container.SaveChanges();
                            }
                            scope.Complete();
                            saveResult = true;
                        }
                        catch(Exception exp)
                        {
                            saveResult = false;
                        }
                    }
                }
            }
            return saveResult;
        }
    }
}
